package com.ujn.spu.controller;

import com.fazecast.jSerialComm.SerialPort;
import com.ujn.spu.core.AjaxResult;
import com.ujn.spu.core.SerialPortManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/opt")
public class OperationController {

    @Autowired
    SerialPortManager serialPortManager;

    private final ConcurrentHashMap<String, SerialPort> serialPortMap = new ConcurrentHashMap<>();

    /**
     * 打开设备
     *
     * @param portName 串口名
     */
    @GetMapping("/port/open/{portName}")
    public AjaxResult openPort(@PathVariable String portName) throws IOException {
        serialPortMap.remove(portName);
        SerialPort currentPort = serialPortManager.openDevice(portName);
        //打开串口失败
        if (null == currentPort){
            return AjaxResult.error("打开设备失败，请检查设备后重试！");
        }
        System.out.println("当前串口："+currentPort);
        serialPortMap.put(portName, currentPort);
        return AjaxResult.success("设备打开成功");
    }

    /**
     *  关闭设备
     */
    @GetMapping("/port/close/{portName}")
    public AjaxResult closePort(@PathVariable String portName){
        if (!serialPortMap.containsKey(portName)){
            return AjaxResult.error("当前未打开任何设备");
        }
        if (serialPortMap.get(portName).closePort()){
            return AjaxResult.success("设备已关闭");
        }
        return AjaxResult.error("关闭设备失败，请检查设备后重试！");
    }

    /**
     * 发送信息
     */
    @PostMapping ("/port/send/{portName}")
    public AjaxResult sendMessage(@PathVariable String portName, String msg){
        if (!serialPortMap.containsKey(portName)){
            return AjaxResult.error("当前未打开设备");
        }
        System.out.println(serialPortMap.get(portName));
        return serialPortManager.sendMessage(serialPortMap.get(portName), msg) ? AjaxResult.success() : AjaxResult.error();
    }
}
